// 这个函数发送一个消息到 MQTT broker
// 只是发送一个消息到一个 topic，消息将会被发送到 broker
function send_mqtt_message(broker_host, broker_port, topic, message) {
    // 构建 broker 的 URL
    const brokerUrl = `mqtt://${broker_host}:${broker_port}`;

    // 连接到 MQTT broker
    const client = mqtt.connect(brokerUrl);

    // 当客户端连接成功时
    client.on('connect', () => {
        console.log('Connected to MQTT broker');

        // 发布消息到指定的 topic
        client.publish(topic, message, (err) => {
            if (err) {
                console.error('Failed to send message:', err);
            } else {
                console.log('Message sent successfully');
            }

            // 断开与 broker 的连接
            client.end();
        });
    });

    // 当连接错误时
    client.on('error', (err) => {
        console.error('Connection error:', err);
        client.end();
    });
}

function send_sensor_light_message(sensor_address, value) {

    var host = window.location.hostname;
    var port = 9001;
    var topic = "iot/devices/test/baina/00000000/allinone/tx";
    var message = "Hello World";

    console.log("host: " + host)
    console.log("port: " + port)
    console.log("topic: " + topic)
    console.log("message: " + message)

    // 发送消息到 MQTT broker
    // 格式：{"task_type": "set_sensor_light", "task_id": "194", "data": {"devaddr_list": ["1"], "value": "01"}}

    // 构建消息对象
    var data = {
        "devaddr_list": [sensor_address],
        "value": value

    }

    var message_obj = {
        "task_type": "set_sensor_light",
        "task_id": "194",
        "data": data
    }

    message = JSON.stringify(message_obj);

    console.log("message: " + message)

    send_mqtt_message(host, port, topic, message);
}

// 示例调用
// send_mqtt_message('broker.hivemq.com', 1883, 'test/topic', 'Hello MQTT');
